package com.test.juc.resource;

import java.util.concurrent.locks.ReentrantLock;

public class Ticket {

    private int ticketNumber = 30;
    private final ReentrantLock lock;

    public Ticket() {
        this.lock = new ReentrantLock();
    }

    public Ticket(boolean isFair) {
        lock = new ReentrantLock(isFair);
    }

    private void decTicket() {
        if (ticketNumber > 0) {
            ticketNumber -= 1;
            System.out.printf("%s 卖出 1 剩下%d\n", Thread.currentThread().getName(), ticketNumber);
        }
    }

    public synchronized void syncSaleTicket() {
        decTicket();
    }

    public void lockSaleTicket() {
        lock.lock();
        try {
            decTicket();
        } finally {
            lock.unlock();
        }
    }
}
